package org.darkforest.common.services.impl;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.darkforest.enums.EmployeeLevel;
import org.darkforest.model.Member;

import java.util.List;

/**
 * LevelDecider
 * Created by Justin on 15/5/31.
 */
public class LevelIndexKey {

    private static final String EMPLOYEE_LEVEL_0_INDEX = "EMPLOYEE_LEVEL_0_INDEX";
    private static final String EMPLOYEE_LEVEL_1_INDEX = "EMPLOYEE_LEVEL_1_INDEX";
    private static final String EMPLOYEE_LEVEL_2_INDEX = "EMPLOYEE_LEVEL_2_INDEX";

    public static String getKey(int level) {
        if (level == 0) {
            return EMPLOYEE_LEVEL_0_INDEX;
        } else if (level == 1) {
            return EMPLOYEE_LEVEL_1_INDEX;
        } else if (level == 2) {
            return EMPLOYEE_LEVEL_2_INDEX;
        }

        throw new IllegalArgumentException("Level " + level + " is illegal. Legal range is [0, 2]");
    }

    public static String getKey(EmployeeLevel level) {
        return getKey(level.ordinal());
    }

    public static Integer getNext(List<Member> members, String index) {
        if (CollectionUtils.isEmpty(members)) {
            throw new IllegalArgumentException("Candidate level members is empty");
        }
        if (StringUtils.isEmpty(index)) {
            return members.get(0).getMemberId();
        }
        Integer indexInt = Integer.valueOf(index);
        return getIndex(members, indexInt);
    }

    private static Integer getIndex(List<Member> members, Integer index) {
        for (int i = 0; i < members.size(); i++) {
            Member member = members.get(i);
            if (member.getMemberId().equals(index)) {
                return i + 1 == members.size() ? members.get(0).getMemberId() : members.get(i + 1).getMemberId();
            }
        }
        return members.get(0).getMemberId();
    }

}
